/**
 * 插件：树形选择器
 * @author zhangGuihua(hua7381@163.com) 
 * @date 2014/03/19
 * 示例：<input data_tree="{type:'res', multi:false, fresh:true, extra:'${yyid}'}"/>
 */
$(function() {
	//自动检测有data_tree属性的控件，为其注册treeSelector
	$("[data_tree]").each(function(){
		$(this).treeSelector();
	});
});

$.fn.extend({
	treeSelector: function() {
		var $h = $(this);
		var $v = $h.prev();
		
		var url = "../sys/tree";
		
		//配置项
		var cfg = eval("("+$h.attr("data_tree")+")");
		if(!cfg.multi) {
			cfg.multi = false;
		}
		if(!cfg.fresh) {
			cfg.fresh = false;
		}
		
		
		//取input的id(无则自动生成)
		if(!$v.attr("id")) {
			$v.attr("id", (Math.random()+"").substring(2));
		}
		var vId = $v.attr("id")
		
		if(!$h.attr("id")) {
			$h.attr("id", (Math.random()+"").substring(2));
		}
		var hId = $h.attr("id")
		
		
		//禁止直接在input中键入文本内容
		$h.keydown(function(){
			return false;
		});
	
		//生成menu ID
		var menuId = (Math.random()+"").substring(2);
		
		//初始化container
		$("body").append("<div id='"+menuId+"' style='width:650px; height:450px;position:absolute; display:none; border:1px solid gray; z-index:9999;'></div>");
		var $menu = $("#"+menuId);
		
		$h.click(function(){
			//在初次打开时加载iframe页面
			if($menu.html() == "" || cfg.fresh) {
				var url2 = url +
					"?menuId="+menuId+
					"&vId="+vId+
					"&hId="+hId+
					"&treeType="+cfg.type+
					"&multiSelect="+cfg.multi+
					"&extra="+cfg.extra+
					"&random="+(Math.random()+"").substring(2);
				$menu.html("<iframe src='"+url2+"' frameborder='0' height='446' width='646'></iframe>");
			}
			
			var left = $h.offset().left;
			if(left + $menu.outerWidth() > $(window).width() - 10) {//确保不超出右边界
				left = $(window).width() - 10 - $menu.outerWidth();
			}
			var top = $h.offset().top+$h.outerHeight();
			
			$menu.css({left: left + "px", top: top+"px"}).show();
		});
		
		$("html").bind("mousedown", function(){
			$menu.hide();
		});
	}
});

/**
 * 供子页面调用:隐藏下拉框
 */
function tree_hideMenu(menuId){
	$("#"+menuId).hide();
}

/**
 * 供子页面调用:返回结果
 */
function tree_returnValue(v, h, vId, hId) {
	if(v!=null){
		$("#"+vId).val(v);
		$("#"+hId).val(h);
		$("#"+hId).focus();
		$("#"+hId).change();
	}
}

